import re
import random
import json
import os
from collections import defaultdict

class CoupletGenerator:
    """
    智能对联生成器
    基于规则和预设数据生成对联
    """
    
    def __init__(self):
        """初始化对联生成器"""
        self.data_path = os.path.join(os.path.dirname(__file__), '../static/data')
        os.makedirs(self.data_path, exist_ok=True)
        
        # 加载对联数据
        self.couplets = self._load_couplets()
        # 加载词语数据
        self.words = self._load_words()
        # 加载韵律数据
        self.rhythm = self._load_rhythm()
        
    def _load_couplets(self):
        """加载预设对联数据"""
        try:
            with open(os.path.join(self.data_path, 'couplets.json'), 'r', encoding='utf-8') as f:
                return json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            default_couplets = {
                "traditional": [
                    {"first": "云对雨，雪对风", "second": "晚照对晴空"},
                    {"first": "山重水复疑无路", "second": "柳暗花明又一村"},
                ],
                "modern": [
                    {"first": "科技改变生活", "second": "创新引领未来"},
                ],
                "humorous": [
                    {"first": "程序员熬夜写代码", "second": "设计师通宵改界面"},
                ]
            }
            with open(os.path.join(self.data_path, 'couplets.json'), 'w', encoding='utf-8') as f:
                json.dump(default_couplets, f, ensure_ascii=False, indent=2)
            return default_couplets
    
    def generate_couplet(self, first_line, style="traditional"):
        """
        根据上联生成下联
        """
        first_line = self._clean_input(first_line)
        if not first_line:
            return {"error": "上联不能为空"}
        
        # 尝试使用规则生成
        second_line = self._rule_based_generation(first_line)
        
        # 如果规则生成失败，尝试使用模式匹配
        if not second_line:
            second_line = self._pattern_matching(first_line, style)
        
        # 如果模式匹配失败，使用随机生成
        if not second_line:
            second_line = self._random_generation(first_line, style)
        
        return {
            "first": first_line,
            "second": second_line
        }
    
    def get_random_couplet(self, style="traditional"):
        """获取随机对联"""
        if style not in self.couplets:
            style = "traditional"
        return random.choice(self.couplets[style])

    # 其他辅助方法...